package com.xxx.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @version v1.0
 * @Description:
 * @Author zhanzhongxin
 * @Date 2021/8/4 14:18
 * @Copyright 博为峰
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final String methodName = req.getParameter("method");
        //1.获取Class对象
//        Class.forName("")
        final Class cla = getClass();
        Method method = null;
        try {
            method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("要调用的方法不存在" + methodName);
        }
        try {
            final String result = (String) method.invoke(this, req, resp);
            final String action = result.substring(0, result.indexOf(":"));
            final String path = result.substring(result.indexOf(":") + 1);
            if (action.equals("forward")) {
                req.getRequestDispatcher(path).forward(req, resp);
            } else if (action.equals("redirect")) {
                resp.sendRedirect(req.getContextPath() + path);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
